#!coding=utf-8
'''
Created on 2016年5月16日

@author: sglnd
'''
import os
import sys
sys.path.append('/home/website/wujiangzto')
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
import django
django.setup()
from django.core.exceptions import ObjectDoesNotExist
import json
from weixin.api.common import sedTempMsg
import time
from wujiangzto.models import PackageInfo
from wujiangzto.views import getBillInfo

def my_scheduled_job():
    print 'i am scheduled'
    try:
        p_all=PackageInfo.objects.exclude(pg_step='3')  # @UndefinedVariable
        for p in p_all:
            wldh=p.pg_id
            step=p.pg_step
            wx_id=p.wx_id
            wuliuinfo=getBillInfo(wldh)
            if wuliuinfo!=0:
                tmp_pro_step='0';
                tmp_pro_name="";
                if(u"签收" in wuliuinfo):
                    tmp_pro_name="sign";
                    tmp_pro_step='3';
                elif(u"派件" in wuliuinfo):
                    tmp_pro_name="delivery";
                    tmp_pro_step='2';
                elif(u"到达" in wuliuinfo):
                    tmp_pro_name="transport";
                    tmp_pro_step='1';
                else:
                    tmp_pro_name="pick-up";
                    tmp_pro_step='0';
                if tmp_pro_step != step:
                    print tmp_pro_step,step
                    #更新包裹状态
                    p.pg_step=tmp_pro_step
                    p.pg_sts=tmp_pro_name
                    p.save()
                    lastinfo=wuliuinfo.split(',')[0].split('+')
#                     info=lastinfo[1]+","+lastinfo[0]
                    info=lastinfo[1]
                    print wx_id,wldh,info
                    tempsendmsg(wx_id,wldh,info)
#如果拿不到物流信息，订单应该为有问题订单，做删除。
            else:
                p.delete()
    except ObjectDoesNotExist:
        return "没有需要处理的订单号"
    

def tempsendmsg(openid,orderno,ordersts):
    msg={
           "touser":openid,
           "template_id":"bUCJG5_qZ5U_isJETXqU2mKFlTd1xEEEoc7y4ELysUM",
           "url":"http://wujiang.wuxizto.com/wuliuinfo/?wldh="+orderno+"&openid="+openid,            
           "data":{
                    "orderNumber":{
                        "value":orderno,
                        "color":"#173177"
                    },
                    "status": {
                        "value":ordersts,
                        "color":"#173177"
                    },
                    "remark":{
                        "value":"谢谢关注吴江中通物流",
                        "color":"#173177"
                    }  
            }
        }
#     encodedjson=json.dumps(msg,ensure_ascii=False);
    encodedjson=json.dumps(msg);
    
#     print encodedjson
    sedTempMsg(encodedjson);
    

while 1 :
    my_scheduled_job()
    print "i am while"
    time.sleep(3000)







    
    
